const gjjGetTokenUrl    = "https://t.51gjj.com/gjj/getToken";
const gjjH5QueryPageUrl = "https://t.51gjj.com/gjj";
const gjjDataUrl        = "http://b.jianbing.com/gjj_v3/gjj/fetch_manual";
const getGjjDataUrl        = "https://t.51gjj.com/gjj/getGjjData";
const oldServerHostDev        = "https://kaifa.jianbing.com";

//php通知接口地址
const notifyUrl     = 'http://b.jianbing.com/ds/gjj/relay/partnersNotify';
const notifyUrl_dev = 'http://kaifa.jianbing.com/ds/gjj/relay/partnersNotify';

const GdGjjData     = 'http://b.jianbing.com/ds/gjj/gd3/order_get_gjj3?order_id=';
const GdGjjData_dev = 'http://kaifa.jianbing.com/ds/gjj/gd3/order_get_gjj3?order_id=';

const refreshUrl    = 'https://t.51gjj.com/postloan/update';

const localIp = '118.24.46.19';


var http       = require('http');
var https      = require('https');
var request    = require('request');
var fs         = require('fs');
var nodeDb     = require('./db');
var DB         = nodeDb.DB;
var myDB       = require('./myDB');
var myAxios    = require('./myAxios');
var url        = require('url');

var config      = require('config');
var parCfg      = config.get('partnerConfig');
var schedule    = require('node-schedule');

var baseServer = require('./gdCommon');
var BS = new Object();
(async function cfgLoading(){
    BS = await baseServer.config(parCfg.cid);
    console.log(BS);
})();

var wsMap = new Map();
var refreshMap = new Map();

var query = async function (req,res){

    try{
        var passport = BS.getParams(req,'userid','');
        var cityId = BS.getParams(req,'cityid','');

        if(!passport){throw "missing userid";}
        if(!cityId){throw "missing cityid";}

        let locationArr = await myDB.getDB("nodeGjjDB").getRowAsync('select * from cfg_location where cid=?',[cityId]);
        if(!locationArr){throw "locationArr error";}
        cityId = locationArr.id;
        if(!cityId){throw "cityId error";}

        let openid  = '';
        let token  = BS.createOldToken();
        if(!token) throw 'get token fail';

        let userInfo = await myDB.getDB("nodeGjjDB").getRowAsync('select * from sys_'+parCfg.prefix+'_user where passport=?',[passport]);

        let userSid = 0;
        if(userInfo){
            userSid = userInfo.sid;
            openid = BS.createOldOpenid(userSid);
            await myDB.getDB("nodeGjjDB").queryAsync('update sys_'+parCfg.prefix+'_user set openid=?,accessToken=? where passport=?',[openid,token,passport]);
        }else{
            let resUser = await myDB.getDB("nodeGjjDB").queryAsync('insert into sys_'+parCfg.prefix+'_user (passport,openid,accessToken,time) value(?,?,?,?)',[passport,openid,token,new Date]);
            userSid = resUser.insertId;
            openid = BS.createOldOpenid(userSid);
            await myDB.getDB("nodeGjjDB").queryAsync('update sys_'+parCfg.prefix+'_user set openid=?,accessToken=? where passport=?',[openid,token,passport]);
        }
        //phone
        if(/^1[3|5][0-9]\d{4,8}$/.test(passport)){
            myDB.getDB("nodeGjjDB").queryAsync('update sys_'+parCfg.prefix+'_user set phone=? where sid=?',[passport,userSid]);
        }

        let data = {
            userSid:userSid,
            openid:openid,
            accessToken:token,
            expires_in:7200
        };

        let partnerCid       = BS.parCfg.cid;
        let reptileAppSecret = BS.parCfg.reptileAppSecret;
        let reptileAppKey    = BS.parCfg.reptileAppKey;

        let redirectUrl = BS.getParams(req, 'redirect', BS.parCfg.returnUrl);
        let callbackUrl = BS.getParams(req, 'callback', BS.parCfg.callbackUrl);

        let  sheToken   = await BS.getTokenToRedis();
        let order   = await BS.getOrder();

        let openH5Log = await myDB.getDB("nodeGjjDB").getRowAsync('select 1 from sys_open_h5_log where userSid=? and orderSn=? and partnerCid=?',[userSid,order,partnerCid]);
        if(openH5Log){
            throw 'open gjj query page fail';
        }

        let requestUrl  = req.url;

        await myDB.getDB("nodeGjjDB").queryAsync('insert into sys_open_h5_log (userSid,orderSn,requestUrl,partnerCid,openid,accessToken,time) value (?,?,?,?,?,?,?)',[userSid,order,requestUrl,partnerCid,openid,token,new Date]);

        let urlParams = [];
        urlParams['appKey']      = reptileAppKey;
        urlParams['orderSn']     = order;
        urlParams['token']       = sheToken;
        urlParams['timestamp']   = +new Date;
        urlParams['sign']        = BS.createSign(urlParams, reptileAppSecret);
        urlParams['redirectUrl'] = '我不跳转';
        urlParams['cid']         = cityId;
        urlParams['selectCity']  = '1';

        let h5Url = "";
        for(x in urlParams){
            if(!h5Url){
                h5Url += '?'+x+'='+urlParams[x];
            }else{
                h5Url += '&'+x+'='+urlParams[x];
            }
        }

        h5Url = gjjH5QueryPageUrl + h5Url;
        console.log(h5Url);

        // let localIp = BS.getLocalInfo('IPv4','address');

        let renderData = {
            url:h5Url,
            linkUrl:localIp+':'+config.get('httpPort')+'/gjj/wsLink?orderSn='+order,
            orderSn:order,
            listenUrl:localIp+':'+config.get('httpPort')+'/gjj/gjjGetTaskInfo'
        }

        var userAgent = '';
        if(req.headers['user-agent']){
            userAgent = req.headers['user-agent'].toLowerCase();
            console.log(userAgent);
            //console.log(req);
        }

        var isOpera = userAgent.indexOf("opera") > -1; //判断是否Opera浏览器
        var isIE = userAgent.indexOf("trident") > -1
             && !isOpera; //判断是否IE浏览器
        var isEdge = userAgent.indexOf("edge") > -1; //判断是否IE的Edge浏览器
        var isFF = userAgent.indexOf("firefox") > -1; //判断是否Firefox浏览器
        var isSafari = userAgent.indexOf("safari") > -1
            && userAgent.indexOf("chrome") == -1; //判断是否Safari浏览器
        var isChrome = userAgent.indexOf("chrome") > -1
            && userAgent.indexOf("safari") > -1; //判断Chrome浏览器

        if(isIE){
            console.log('IE');
            res.redirect(h5Url+'&type=pc');
        }else{
            console.log('onIE');
            res.render('Query',renderData);
        }

    }catch(error){
        res.send({peroject:BS.parCfg.name,code:-1,msg:error});
    }

}

/** 光大数据拉取 ***/
var getGjjData = async function (orderSn,body){
    let url = GdGjjData_dev+orderSn;
    let params = body;
    let result = await myAxios.post(url,params, {headers: {'Content-Type': 'application/json'}});
    if(!result.data){
        console.error("[gdBank/getGjjData] gjj data error : "+JSON.stringify(result));
        return {
            "Head": {
                "ErrCode": "999"
            },
            "Body": {
                "ErrCode2": "999",
                "ErrCode3": "-1",
                "ErrorInfo": "拉取公积金数据异常，联系51公积金 error:("+JSON.stringify(result)+")",
                "ErrCode": "999"
            }
        };
    }
    let data = result.data;
    if(!data.Head || !data.Head.ErrCode || data.Head.ErrCode!=0){
        console.error(result.data);
    }
    return data;
}

/** 光大数据拉取 ***/
var get = async function (req,res){
    try{
        var passport = BS.getParams(req,'userid','');
        var refresh = BS.getParams(req,'refresh','');
        if(!passport){
            throw "missing userid";
        }
        var userArr = await myDB.getDB("nodeGjjDB").getRowAsync('select sid from sys_'+parCfg.prefix+'_user where passport=?',[passport]);
        if(!userArr){
            throw "userid error";
        }
        var userSid = userArr.sid;
        let surnameArr = await myDB.getDB("nodeGjjDB").getRowAsync('select orderSn,refreshTime from sys_surname where userSid=? and partnerCid=? order by refreshTime desc limit 1',[userSid,parCfg.cid]);
        if(!surnameArr){
            throw "not surname";
        }
        var orderSn = surnameArr.orderSn;
        //光大刷新条件
        let refreshTime = new Date(surnameArr.refreshTime).getHours();
        if(refreshTime<8 || refresh==1){
            refreshMap.set(orderSn, {res:res,body:req.body});
            var ret = refreshGjj(orderSn);
        }else{
            let data = await getGjjData(orderSn,req.body);
            res.send({code:200,data:data});
        }

    }catch (error){
        console.error('['+BS.parCfg.name+'/testGet] msg '+error);
        res.send({code:-1,msg:error});
    }
}

var oldQuery = async function (req,res){
    try {
        let cityId = BS.getParams(req,'cityid',0);
        if(!cityId){
            throw 'missing cityid';
        }
        let userId = BS.getParams(req,'userid','');
        if(!userId){
            throw 'missing userid';
        }
        let redirect = oldServerHostDev + '/hs/gdgjj/c' + cityId + '?userid=' + userId;
        res.redirect(redirect);
    }catch(error){
        console.error(error);
        res.send({code:-1,msg:error});
    }
}
var oldGet = async function (req,res){
    //test
    try {
        let ID = BS.getParams(req,'id','');
        let userId = BS.getParams(req,'userid','');
        if(!userId){
            throw 'missing userid';
        }
        let url = oldServerHostDev+'/ds/gjj/gd/get_gjj';
        let params = {
            Head:{
                sign:'gdBank node'
            },
            Body:{
                userid:userId,
                std400idno:ID
            }
        }
        let ret = myAxios.post();
    }catch(error){
        res.send({code:-1,msg:error});
    }
}

/** 查询回调 ***/
var gjjCallBack2 = async function (req,res){
    console.log('【'+BS.parCfg.name+'】【gjjCallBack2】【in】'+JSON.stringify(req.body));
    try{

        let partnerCid       = BS.parCfg.cid;

        //接受成功任务回调，调制参数并回调服务端后端
        let orderSn     = BS.getParams(req,'order_id','');//订单编号
        //刷新任务的订单
        if(orderSn){
            let orderSn     = BS.getParams(req,'orderSn','');//订单编号
        }
        let taskStatus  = (BS.getParams(req,'status','')=='success')?1:0;//任务状态
        let userId      = BS.getParams(req,'user_id','');//用户标号
        // let taskType = BS.getParams(req,'taskType','');
        let taskMsg     = BS.getParams(req,'status','');//任务描述
        let timestamp   = BS.getParams(req,'timestamp','');//结束时间
        let cityId      = BS.getParams(req,'cityId','');//城市编号

        //刷新任务
        if(refreshMap.get(orderSn)){
            let orderInfo = refreshMap.get(orderSn);
            let data = await getGjjData(orderInfo.body);
            orderInfo.res.send(data);
        }

        //打开页面的记录
        let arrH5log = await myDB.getDB('nodeGjjDB').getRowAsync('select userSid,requestUrl,time from sys_open_h5_log where orderSn=? and partnerCid=?',[orderSn,partnerCid]);
        if(!arrH5log){
            console.error('orderSn='+orderSn+' 没有记录');
            throw '没有这次任务';
        }

        let userSid    = arrH5log.userSid;
        let requestUrl = arrH5log.requestUrl;
        let createTime = arrH5log.time;

        //记录这笔成功的订单,订单列表
        var dbParam = [userSid, partnerCid, orderSn, taskStatus, taskMsg, cityId, createTime, new Date, 1];
        let resOrder = await myDB.getDB('nodeGjjDB').queryAsync('insert into sys_order_list (userSid,partnerCid,orderSn,taskStatus,taskMsg,cityId,createTime,callbackTime,taskType) value (?,?,?,?,?,?,?,?,?)',dbParam);
        let orderSid = resOrder.insertId;

        //找到订单对应的用户
        let arrUser = await myDB.getDB('nodeGjjDB').getRowAsync('select passport from sys_'+parCfg.prefix+'_user where sid=?',[userSid]);
        if(!arrUser){
            console.error('userSid='+userSid+' 没有这个用户');
            throw '没有这个用户';
        }
        let passport = arrUser.passport;


        let gjjSid     = 0;
        let loanSid    = 0;
        let surnameSid = 0;
        //任务成功
        if(taskStatus==1){
            //获取公积金关键参数
            let gjjSign = await BS.getGjjSign(orderSn);
            if(!gjjSign){throw "gjj data empty";}
            let gjjDataSign = BS.getValue(gjjSign,'gjjDataSign');
            let mainParams = BS.getValue(gjjSign,'params');

            console.log('【'+BS.parCfg.name+'/gjjCallBack2】new gjj '+JSON.stringify(mainParams));//debug

            let ID     = BS.getValue(mainParams,'ID');
            let cityId = BS.getValue(mainParams,'cityId');
            let name   = BS.getValue(mainParams,'name');
            let ifLoan = BS.getValue(mainParams,'ifLoan');//判断是否有贷款信息

            if(cityId){
                await myDB.getDB('nodeGjjDB').queryAsync('update sys_order_list set cityId=? where orderSn=?',[cityId, orderSn]);
            }

            //while todo加密脱敏

            //公积金信息编号
            let arrGjj = await myDB.getDB("nodeGjjDB").getRowAsync('select sid from sys_gjj where ID=? and cityId=?',[ID,cityId]);
            if(arrGjj){
                gjjSid = arrGjj.sid;
            }else{
                let resGjj = await myDB.getDB("nodeGjjDB").queryAsync('insert into sys_gjj (name,ID,cityId) value (?,?,?)',[name,ID,cityId]);
                gjjSid = resGjj.insertId;
                if(gjjSid){
                    console.log('【'+BS.parCfg.name+'/gjjCallBack2】new gjjSid='+gjjSid+' sql=insert into sys_gjj (name,ID,cityId) value ('+name+','+ID+','+cityId+')');
                }
            }
            //贷款信息编号
            if(ifLoan){
                let arrLoan = await myDB.getDB("nodeGjjDB").getRowAsync('select sid from sys_loan where ID=? and cityId=?',[ID,cityId]);
                if(arrLoan){
                    loanSid = arrLoan.sid;
                }else{
                    let resLoan = await myDB.getDB("nodeGjjDB").queryAsync('insert into sys_loan (name,ID,cityId) value (?,?,?)',[name,ID,cityId]);
                    loanSid = resLoan.insertId;
                    if(loanSid){
                        console.log('【'+BS.parCfg.name+'/gjjCallBack2】new loanSid='+loanSid+' sql=insert into sys_loan (name,ID,cityId) value ('+name+','+ID+','+cityId+')');
                    }
                }
            }

            console.log('【'+BS.parCfg.name+'】【gjjCallBack2】'+JSON.stringify({gjjSid:gjjSid,loanSid:loanSid}));

            //用户公积金关联
            let arrSurname = await myDB.getDB('nodeGjjDB').getRowAsync('select * from sys_surname where userSid=? and gjjSid=? and cityId=?',[userSid,gjjSid,cityId]);
            if(arrSurname){
                //更新account
                await myDB.getDB('nodeGjjDB').queryAsync('update sys_surname set orderSn=?,refreshTime=? where userSid=? and gjjSid=?',[orderSn, new Date, userSid, gjjSid]);
                surnameSid = arrSurname.sid;

            }else{
                let resSurname = await myDB.getDB('nodeGjjDB').queryAsync('insert into sys_surname (userSid,orderSn,loanSid,gjjSid,partnerCid,cityId,addTime,refreshTime) value (?,?,?,?,?,?,?,?)',[userSid, orderSn, loanSid, gjjSid, partnerCid, cityId, new Date, new Date]);
                if(!resSurname){
                    console.error('【'+BS.parCfg.name+'】【gjjCallBack2】insert into surname fail');
                    throw 'insert into surname fail';
                }
                surnameSid = resSurname.insertId;
            }
        }

        //后端回调地址
        let callbackUrl = BS.parCfg.callbackUrl;
        //前端跳转地址
        let redirectUrl = BS.getValue(url.parse(requestUrl, true).query,'redirect',BS.parCfg.redirectUrl) || BS.parCfg.callbackUrl;

        let sendData = {
            code:0,
            data:{
                u:passport,
                job_sid:orderSid,
                surname_sid:surnameSid,
                result:taskMsg,
                state:2,
            },
            yys_cid:45,
            notifyUrl:callbackUrl
        };

        if(!callbackUrl){
            console.error('[wld/gjjCallBack2] 回调地址错误 '+ JSON.stringify(callbackUrl));
        }
        sendData.notifyUrl = sendData.notifyUrl+'?d='+encodeURIComponent(JSON.stringify(sendData.data));

        let WebData = {
            uid:passport,
            gjj_sid:surnameSid,
            redirectUrl:redirectUrl
        }

        // console.log('【'+BS.parCfg.name+'】【gjjCallBack2】【out】'+userSid+'--'+passport+'--'+orderSid+'--'+surnameSid+'--'+cid+'--'+sendData['notifyUrl']);
        console.log('【'+BS.parCfg.name+'/gjjCallBack2】【out】'+JSON.stringify(sendData));

        //后端通知合作方
        // BS.notify(notifyUrl,sendData);
        // BS.notify(notifyUrl_dev,sendData);
        //通知客户端
        // BS.notify(socketHost+'/ws/notify',sendData);
        notifyWeb(orderSn,WebData);

        res.send({'errcode':0,'msg':'ok','data':{'userSid':userSid,'passport':passport,'surnameSid':surnameSid}});

    }catch(err){
        console.error(err);
        data = {'errcode':-1,'msg':err}
        res.send(data);
    }
}

/** 刷新公积金 ***/
var refreshGjj = async function(orderSn){
    console.log('[gdBank/refreshGjj] refresh '+orderSn);
    //refresh接口刷新，等待回调通知;
    var params = {
        sign: "",
        type: "gjj",
        param: {
            timestamp: +new Date,
            appKey: BS.parCfg.reptileAppKey,
            orderSn: orderSn,
            token: await BS.getTokenToRedis()
        },
        callbackUrl: "http://"+localIp+":"+config.get('httpPort')+"/gjj/refreshCallback"
    }
    params.sign = BS.createSign(params.param, BS.parCfg.reptileAppSecret);

    var ret = await myAxios.post(refreshUrl,params, {headers: {'Content-Type': 'application/json'}});
    if(ret.data){
        if(ret.data.code!=0){
            console.error(params);
            console.error('[gdBank/refreshGjj] refresh fail '+JSON.stringify(ret));
        }
    }

}

/** 刷新回调 ***/
var refreshCallback = async function (req,res){
    console.log('【'+BS.parCfg.name+'】【refreshCallback】【in】'+JSON.stringify(req.body));
    try{
        let partnerCid       = BS.parCfg.cid;
        //接受成功任务回调，调制参数并回调服务端后端
        let orderSn     = BS.getParams(req,'orderSn','');//订单编号
        let taskStatus  = (BS.getParams(req,'msg','')=='success')?1:0;//任务状态(success/failed)
        let code        = BS.getParams(req,'code','');//任务状态(success/failed)
        let taskMsg     = BS.getParams(req,'msg','');//任务描述
        let timestamp   = BS.getParams(req,'timestamp','');//结束时间
        let cityId      = BS.getParams(req,'cityId','');//城市编号

        //刷新任务
        if(refreshMap.get(orderSn)){
            let orderInfo = refreshMap.get(orderSn);
            if(taskStatus==1 && code==0){
                let data = await getGjjData(orderSn,orderInfo.body);
                orderInfo.res.send(data);
            }else{
                orderInfo.res.send({
                    "Head": {
                        "ErrCode": "999"
                    },
                    "Body": {
                        "ErrCode2": "999",
                        "ErrCode3": "-1",
                        "ErrorInfo": taskMsg,
                        "ErrCode": "999"
                    }
                });
            }
        }

        let surnameArr = await myDB.getDB('nodeGjjDB').getRowAsync('select userSid from sys_surname where orderSn=? and partnerCid=?',[orderSn,partnerCid]);
        if(!surnameArr){
            console.error('userSid='+userSid+' 没有这个用户');
            throw '没有这个用户';
        }

        var userSid = surnameArr.userSid;

        //记录这笔成功的订单,订单列表
        var dbParam = [userSid, partnerCid, orderSn, taskStatus, taskMsg, cityId, new Date, new Date, 2];
        let resOrder = await myDB.getDB('nodeGjjDB').queryAsync('insert into sys_order_list (userSid,partnerCid,orderSn,taskStatus,taskMsg,cityId,createTime,callbackTime,taskType) value (?,?,?,?,?,?,?,?,?)',dbParam);

        //找到订单对应的用户
        let arrUser = await myDB.getDB('nodeGjjDB').getRowAsync('select passport from sys_'+parCfg.prefix+'_user where sid=?',[userSid]);
        if(!arrUser){
            console.error('userSid='+userSid+' 没有这个用户');
            throw '没有这个用户';
        }
        let passport = arrUser.passport;


        let gjjSid     = 0;
        let loanSid    = 0;
        //任务成功
        if(taskStatus==1){
            //获取公积金关键参数
            let gjjSign = await BS.getGjjSign(orderSn);
            if(!gjjSign){throw "gjj data empty";}
            let gjjDataSign = BS.getValue(gjjSign,'gjjDataSign');
            let mainParams = BS.getValue(gjjSign,'params');

            console.log('【/refreshCallback】new gjj '+JSON.stringify(mainParams));//debug

            let ID     = BS.getValue(mainParams,'ID');
            let cityId = BS.getValue(mainParams,'cityId');
            let name   = BS.getValue(mainParams,'name');
            let ifLoan = BS.getValue(mainParams,'ifLoan');//判断是否有贷款信息

            //补全城市编号
            if(cityId){
                await myDB.getDB('nodeGjjDB').queryAsync('update sys_order_list set cityId=? where orderSn=?',[cityId, orderSn]);
            }

            //收入公积金信息编号
            let arrGjj = await myDB.getDB("nodeGjjDB").getRowAsync('select sid from sys_gjj where ID=? and cityId=?',[ID,cityId]);
            if(arrGjj){
                gjjSid = arrGjj.sid;
            }else{
                let resGjj = await myDB.getDB("nodeGjjDB").queryAsync('insert into sys_gjj (name,ID,cityId) value (?,?,?)',[name,ID,cityId]);
                gjjSid = resGjj.insertId;
                if(gjjSid){
                    console.log('【/refreshCallback】new gjjSid='+gjjSid+' sql=insert into sys_gjj (name,ID,cityId) value ('+name+','+ID+','+cityId+')');
                }
            }
            //收入贷款信息编号
            if(ifLoan){
                let arrLoan = await myDB.getDB("nodeGjjDB").getRowAsync('select sid from sys_loan where ID=? and cityId=?',[ID,cityId]);
                if(arrLoan){
                    loanSid = arrLoan.sid;
                }else{
                    let resLoan = await myDB.getDB("nodeGjjDB").queryAsync('insert into sys_loan (name,ID,cityId) value (?,?,?)',[name,ID,cityId]);
                    loanSid = resLoan.insertId;
                    if(loanSid){
                        console.log('【/refreshCallback】new loanSid='+loanSid+' sql=insert into sys_loan (name,ID,cityId) value ('+name+','+ID+','+cityId+')');
                    }
                }
            }

            console.log('【'+BS.parCfg.name+'】【refreshCallback】'+JSON.stringify({gjjSid:gjjSid,loanSid:loanSid}));

            //用户公积金关联
            let arrSurname = await myDB.getDB('nodeGjjDB').getRowAsync('select * from sys_surname where userSid=? and gjjSid=? and cityId=?',[userSid,gjjSid,cityId]);
            if(arrSurname){
                //更新account
                await myDB.getDB('nodeGjjDB').queryAsync('update sys_surname set orderSn=?,refreshTime=? where userSid=? and gjjSid=?',[orderSn, new Date, userSid, gjjSid]);

            }else{
                let resSurname = await myDB.getDB('nodeGjjDB').queryAsync('insert into sys_surname (userSid,orderSn,loanSid,gjjSid,partnerCid,cityId,addTime,refreshTime) value (?,?,?,?,?,?,?,?)',[userSid, orderSn, loanSid, gjjSid, partnerCid, cityId, new Date, new Date]);
                if(!resSurname){
                    console.error('【'+BS.parCfg.name+'】【refreshCallback】insert into surname fail');
                    throw 'insert into surname fail';
                }
            }
        }

        res.send({'errcode':0,'msg':'ok'});

    }catch(err){
        console.error('refreshCallback'+JSON.stringify(err));
        data = {'errcode':-1,'msg':err}
        res.send(data);
    }
}

/** 任务状态轮询 ***/
var gjjGetTaskInfo = async function (req,res){
    try{
        let orderSn = BS.getParams(req,'orderSn','');
        let orderArr = await myDB.getDB("nodeGjjDB").getRowAsync('select (1) from sys_order_list where orderSn=?',[orderSn]);
        if(!orderArr){throw "";}
        let h5LogArr = await myDB.getDB("nodeGjjDB").getRowAsync('select userSid,requestUrl,partnerCid from sys_open_h5_log where orderSn=?',[orderSn]);
        if(!h5LogArr){throw "";}
        let userArr = await myDB.getDB("nodeGjjDB").getRowAsync('select passport from sys_'+parCfg.prefix+'_user where sid=?',[h5LogArr.userSid]);
        if(!userArr){throw "";}
        let surnameArr = await myDB.getDB("nodeGjjDB").getRowAsync('select sid from sys_surname where userSid=? orderSn=? partnerCid=?',[h5LogArr.userSid,orderSn,BS.parCfg.cid]);
        if(!surnameArr){throw "";}
        let redirectUrl = h5LogArr.requestUrl+'?uid='+userArr.passport+'&gjj_sid='+surnameArr.sid;
        res.send({code:0,state:'ok',data:{redirectUrl:redirectUrl}});
    }catch(err){
        res.send({code:-1,state:'no'});
    }
}

/** 页面长连接 ***/
var wsLink = function (ws,req){
    // ws = ws.ws;
    // req = req.req;

    //没有订单号
    if (!req.query.orderSn) {
        return;
    }

    let orderSn =  String(req.query.orderSn);
    console.log('orderSn '+orderSn);

    // /*根据订单号存储连接*/
    wsMap.set(orderSn, ws);

    try {
        ws.send('ok');
    } catch (err) {
        console.error(err);
    }
    console.log('[GJJ ws] 连接数' + wsMap.size);

    /*接收信息*/
    ws.on('message', function (msg) {

        // if (msg.indexOf('name' > -1)) {
        //     msg = JSON.parse(msg);
        //     if (orderIdMap.has(String(req.query.taskId))) {
        //         orderIdMap.get(String(req.query.taskId)).needGeneral = 1;
        //         orderIdMap.get(String(req.query.taskId)).name = msg.name;
        //         orderIdMap.get(String(req.query.taskId)).ID = msg.ID;
        //         orderIdMap.get(String(req.query.taskId)).phone = msg.phone;
        //         console.log(orderIdMap.get(String(req.query.taskId)));
        //     }
        // }
        console.log(msg);
    });

    /*断开连接*/
    ws.on('close', function () {
        if (wsMap.has(orderSn)) {
            wsMap.delete(orderSn);
            console.log('[GJJ]ws连接断开');
        }
    });
}

/** 长连接发送 ***/
var wsSendBack = function (orderSn, data) {
    if(wsMap.get(orderSn)){
        console.log('[ws/notifyWeb] success orderSn='+orderSn+' data='+JSON.stringify(data));
        wsMap.get(orderSn).send(JSON.stringify(data));//发送
    }else{
        console.error('[phpws/result] Link loss (没有找到长连接) orderSn='+orderSn);
    }
}

/** 前端通知 ***/
var notifyWeb = function (orderSn,webData){
    console.log('[ws/notifyWeb] orderSn='+orderSn+' webData'+JSON.stringify(webData));
    try{
        if(!orderSn){
            throw "empty orderSn";
        }
        if(!webData.redirectUrl){
            throw "empty redirectUrl";
        }

        //等待10秒
        let item = 10;
        if(wsMap.get(orderSn)){
            wsSendBack(orderSn, webData);
        }else{
            //等待
            let myTime = setInterval(function(){
                console.log('[ws/notifyWeb]loading....'+orderSn);
                item--;
                if(wsMap.get(orderSn)){
                    clearInterval(myTime);
                    wsSendBack(orderSn, webData);
                }else if(item<0){
                    clearInterval(myTime);
                }
            },1000);
        }

        return true;

    }catch(err){
        console.error('[ws/notifyWeb]'+JSON.stringify(err));
        return false;
    }

}

/** 数据拉取 ***/
var fetchManual = async function (req,res){

    let orderSn = BS.getParams(req,'order_sn','');
    console.log('【'+BS.parCfg.name+'/fetchManual】【in】order_sn='+orderSn);

    let gjjData = await BS.getGjjData(orderSn);
    if(gjjData.code==-1 && gjjData.msg=='token已失效'){
        BS.getTokenToRedis(7200, true);
    }else if(gjjData.code==200){
        gjjData.code = 0;
    }
    console.log('【'+BS.parCfg.name+'/fetchManual】【out】'+JSON.stringify(gjjData).substr(0,100));
    res.send(gjjData);
}

/** 获取订单号 ***/
var getOrder = async function (req,res) {
    console.log('【'+BS.parCfg.name+'】【getOrder】【in】url='+req.url+' '+JSON.stringify(req.body));
    try{
        let gjjSid = BS.getParams(req,'surnameSid',0);
        let parCid = BS.getParams(req,'partnerCid',0);

        let arrSurname = await myDB.getDB('nodeGjjDB').getRowAsync('select * from sys_surname where sid=? and partnerCid=?',[gjjSid,parCid]);

        if(!arrSurname){
            console.log('gjjSid='+gjjSid);
            throw 'wld getOrder fail';
        }

        let orderSn = BS.getValue(arrSurname,'orderSn','');
        let surnameSid = BS.getValue(arrSurname,'sid','');
        let loanSid = BS.getValue(arrSurname,'loanSid','');

        let outParams = {
            'code':0,
            'data':{
                'orderSn':orderSn,
                'surnameSid':surnameSid,
                'gjjSid':gjjSid,
                'loanSid':loanSid
            }
	    }
	    console.log('【'+BS.parCfg.name+'】【getOrder】【out】'+JSON.stringify(outParams));
        res.send(outParams);
    }catch(error){
        console.error('【'+BS.parCfg.name+'】【getOrder】'+JSON.stringify(error));
        res.send({'code':101,'msg':error});
    }
}

var refreshToken  = async function(req,res){
    res.send(await BS.getTokenToRedis(7200, true));
}

//测试接口
var test = async function (req,res) {
    console.log(req);
    let order = BS.getParams(req,'order_id','');
    console.log(order);
    let data = BS.getParams(req,'data','');
    notifyWeb(order,data);
    res.send('ok');
    // let str = '330382199204020475';
    // str = BS.rsaEncrypt(str,'rsa_51gjj_public_key_dev.pem');
    // console.log('加密'+str);
    // str = BS.rsaDecrypt(str,'rsa_51gjj_private_key_dev.pem');
    // console.log('解密'+str);
    // res.send(str);
}

//每第5天的凌晨 04:00:00
var j = schedule.scheduleJob('0 4 * * *', function(){
    console.log('[gd/clear] clear sys_'+parCfg.prefix+'_user');
});


exports.gjjQuery    = query;
exports.gjjGet      = get;
exports.oldQuery = oldQuery;
exports.oldGet   = oldGet;

exports.gjjCallBack  = gjjCallBack2;
exports.fetchManual  = fetchManual;
exports.getOrder     = getOrder;
exports.refreshToken = refreshToken;

exports.test         = test;
exports.wsLink       = wsLink;
exports.gjjGetTaskInfo       = gjjGetTaskInfo;
exports.refreshCallback       = refreshCallback;


